<template>
  <div class="bi-dashboard-page">
    <div class="page-header">
      <h2>BI商业智能看板</h2>
      <div class="header-actions">
        <el-button type="primary" icon="Setting" @click="showSettingsDialog = true">看板设置</el-button>
        <el-button icon="Share">分享</el-button>
        <el-button icon="Download">导出报告</el-button>
      </div>
    </div>

    <!-- 时间范围选择 -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="filterForm">
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :shortcuts="dateShortcuts"
          />
        </el-form-item>
        <el-form-item label="对比维度">
          <el-select v-model="filterForm.compareType" placeholder="选择对比维度">
            <el-option label="同比" value="yoy" />
            <el-option label="环比" value="mom" />
            <el-option label="定基比" value="fixed" />
          </el-select>
        </el-form-item>
        <el-form-item label="数据粒度">
          <el-select v-model="filterForm.granularity" placeholder="选择粒度">
            <el-option label="日" value="day" />
            <el-option label="周" value="week" />
            <el-option label="月" value="month" />
            <el-option label="季" value="quarter" />
            <el-option label="年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleSearch">查询</el-button>
          <el-button icon="Refresh" @click="handleRefresh">刷新</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 核心指标卡片 -->
    <el-row :gutter="20" class="kpi-row">
      <el-col :span="6" v-for="kpi in kpiList" :key="kpi.id">
        <div class="kpi-card" :class="kpi.trend > 0 ? 'positive' : 'negative'">
          <div class="kpi-icon" :style="{ background: kpi.color }">
            <el-icon :size="32"><component :is="kpi.icon" /></el-icon>
          </div>
          <div class="kpi-content">
            <div class="kpi-label">{{ kpi.label }}</div>
            <div class="kpi-value">{{ kpi.value }}</div>
            <div class="kpi-footer">
              <span class="kpi-compare">
                <el-icon><component :is="kpi.trend > 0 ? 'CaretTop' : 'CaretBottom'" /></el-icon>
                {{ Math.abs(kpi.trend) }}%
              </span>
              <span class="kpi-desc">{{ kpi.compareText }}</span>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 主要数据看板 -->
    <el-row :gutter="20">
      <!-- 销售趋势 -->
      <el-col :span="16">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span class="title">销售趋势分析</span>
              <el-radio-group v-model="salesChartType" size="small">
                <el-radio-button label="line">折线图</el-radio-button>
                <el-radio-button label="bar">柱状图</el-radio-button>
                <el-radio-button label="area">面积图</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div ref="salesChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 销售占比 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <span class="title">销售渠道占比</span>
          </template>
          <div ref="channelChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行图表 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 区域销售 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span class="title">区域销售分布</span>
          </template>
          <div ref="regionChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 产品类别 -->
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <span class="title">产品类别销售</span>
          </template>
          <div ref="categoryChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行图表 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 客户分析 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <span class="title">客户价值分析</span>
          </template>
          <div ref="customerValueChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 库存周转 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <span class="title">库存周转分析</span>
          </template>
          <div ref="inventoryTurnoverChartRef" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 利润分析 -->
      <el-col :span="8">
        <el-card class="chart-card">
          <template #header>
            <span class="title">利润率趋势</span>
          </template>
          <div ref="profitChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据明细表 -->
    <el-card class="table-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span class="title">详细数据表</span>
          <div>
            <el-button size="small" icon="Download">导出数据</el-button>
            <el-button size="small" icon="Refresh" @click="refreshTable">刷新</el-button>
          </div>
        </div>
      </template>

      <el-tabs v-model="activeTableTab">
        <el-tab-pane label="销售明细" name="sales">
          <el-table :data="salesDetailData" stripe max-height="400">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column prop="channel" label="渠道" width="120" />
            <el-table-column prop="region" label="区域" width="120" />
            <el-table-column prop="orders" label="订单数" width="100" align="right" />
            <el-table-column prop="revenue" label="销售额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ row.revenue.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="cost" label="成本" width="120" align="right">
              <template #default="{ row }">
                ¥{{ row.cost.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="profit" label="利润" width="120" align="right">
              <template #default="{ row }">
                <span :style="{ color: row.profit > 0 ? '#67c23a' : '#f56c6c' }">
                  ¥{{ row.profit.toLocaleString() }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="profitRate" label="利润率" width="100" align="right">
              <template #default="{ row }">
                {{ row.profitRate }}%
              </template>
            </el-table-column>
            <el-table-column prop="yoyGrowth" label="同比增长" width="100" align="right">
              <template #default="{ row }">
                <span :style="{ color: row.yoyGrowth > 0 ? '#67c23a' : '#f56c6c' }">
                  {{ row.yoyGrowth > 0 ? '+' : '' }}{{ row.yoyGrowth }}%
                </span>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="产品排行" name="products">
          <el-table :data="productRankData" stripe max-height="400">
            <el-table-column prop="rank" label="排名" width="80" align="center">
              <template #default="{ row }">
                <el-tag v-if="row.rank <= 3" :type="getRankType(row.rank)">
                  {{ row.rank }}
                </el-tag>
                <span v-else>{{ row.rank }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="产品名称" min-width="200" />
            <el-table-column prop="category" label="类别" width="120" />
            <el-table-column prop="salesVolume" label="销量" width="100" align="right" />
            <el-table-column prop="revenue" label="销售额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ row.revenue.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="growth" label="增长率" width="100" align="right">
              <template #default="{ row }">
                <span :style="{ color: row.growth > 0 ? '#67c23a' : '#f56c6c' }">
                  {{ row.growth > 0 ? '+' : '' }}{{ row.growth }}%
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="marketShare" label="市场占比" width="120" align="center">
              <template #default="{ row }">
                <el-progress :percentage="row.marketShare" />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <el-tab-pane label="客户分析" name="customers">
          <el-table :data="customerAnalysisData" stripe max-height="400">
            <el-table-column prop="customerName" label="客户名称" width="200" />
            <el-table-column prop="level" label="客户等级" width="100">
              <template #default="{ row }">
                <el-tag>{{ row.level }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="totalOrders" label="订单总数" width="100" align="right" />
            <el-table-column prop="totalRevenue" label="累计销售额" width="120" align="right">
              <template #default="{ row }">
                ¥{{ row.totalRevenue.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="avgOrderValue" label="客单价" width="120" align="right">
              <template #default="{ row }">
                ¥{{ row.avgOrderValue.toLocaleString() }}
              </template>
            </el-table-column>
            <el-table-column prop="rfmScore" label="RFM评分" width="100" align="center" />
            <el-table-column prop="lastOrderDate" label="最近交易" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getCustomerStatusType(row.status)">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 看板设置对话框 -->
    <el-dialog v-model="showSettingsDialog" title="看板设置" width="600px">
      <el-form :model="settingsForm" label-width="100px">
        <el-form-item label="刷新频率">
          <el-select v-model="settingsForm.refreshInterval">
            <el-option label="不自动刷新" :value="0" />
            <el-option label="每30秒" :value="30" />
            <el-option label="每1分钟" :value="60" />
            <el-option label="每5分钟" :value="300" />
            <el-option label="每10分钟" :value="600" />
          </el-select>
        </el-form-item>
        <el-form-item label="默认时间范围">
          <el-select v-model="settingsForm.defaultTimeRange">
            <el-option label="今天" value="today" />
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
            <el-option label="本季度" value="quarter" />
            <el-option label="本年" value="year" />
          </el-select>
        </el-form-item>
        <el-form-item label="显示模块">
          <el-checkbox-group v-model="settingsForm.visibleModules">
            <el-checkbox label="sales">销售分析</el-checkbox>
            <el-checkbox label="inventory">库存分析</el-checkbox>
            <el-checkbox label="customer">客户分析</el-checkbox>
            <el-checkbox label="product">产品分析</el-checkbox>
            <el-checkbox label="profit">利润分析</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="数据粒度">
          <el-radio-group v-model="settingsForm.defaultGranularity">
            <el-radio label="day">日</el-radio>
            <el-radio label="week">周</el-radio>
            <el-radio label="month">月</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showSettingsDialog = false">取消</el-button>
        <el-button type="primary" @click="saveSettings">保存设置</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 筛选表单
const filterForm = reactive({
  dateRange: [],
  compareType: 'yoy',
  granularity: 'day'
})

// 日期快捷选项
const dateShortcuts = [
  {
    text: '最近一周',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近一个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  },
  {
    text: '最近三个月',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
      return [start, end]
    }
  }
]

// KPI数据
const kpiList = ref([
  {
    id: 1,
    label: '总销售额',
    value: '¥15.8M',
    trend: 12.5,
    compareText: '较上月',
    icon: 'Money',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
  },
  {
    id: 2,
    label: '订单总数',
    value: '12,586',
    trend: 8.3,
    compareText: '较上月',
    icon: 'Document',
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)'
  },
  {
    id: 3,
    label: '客户总数',
    value: '2,856',
    trend: 15.2,
    compareText: '较上月',
    icon: 'User',
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)'
  },
  {
    id: 4,
    label: '毛利率',
    value: '38.5%',
    trend: -2.1,
    compareText: '较上月',
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)'
  }
])

// 图表类型
const salesChartType = ref('line')
const activeTableTab = ref('sales')

// 表格数据
const salesDetailData = ref([
  {
    date: '2025-01-10',
    channel: '线上',
    region: '华东',
    orders: 586,
    revenue: 1258000,
    cost: 856000,
    profit: 402000,
    profitRate: 31.9,
    yoyGrowth: 12.5
  },
  {
    date: '2025-01-10',
    channel: '线下',
    region: '华南',
    orders: 432,
    revenue: 985000,
    cost: 685000,
    profit: 300000,
    profitRate: 30.5,
    yoyGrowth: 8.3
  }
])

const productRankData = ref([
  {
    rank: 1,
    productName: 'iPhone 15 Pro',
    category: '手机',
    salesVolume: 1285,
    revenue: 15850000,
    growth: 18.5,
    marketShare: 32
  },
  {
    rank: 2,
    productName: 'MacBook Air M3',
    category: '电脑',
    salesVolume: 856,
    revenue: 12580000,
    growth: 12.3,
    marketShare: 25
  },
  {
    rank: 3,
    productName: 'AirPods Pro',
    category: '配件',
    salesVolume: 2156,
    revenue: 5850000,
    growth: 25.6,
    marketShare: 18
  }
])

const customerAnalysisData = ref([
  {
    customerName: '华为技术有限公司',
    level: 'VIP',
    totalOrders: 156,
    totalRevenue: 2850000,
    avgOrderValue: 18269,
    rfmScore: 95,
    lastOrderDate: '2025-01-10',
    status: '活跃'
  },
  {
    customerName: '阿里巴巴集团',
    level: '重要',
    totalOrders: 128,
    totalRevenue: 1980000,
    avgOrderValue: 15469,
    rfmScore: 88,
    lastOrderDate: '2025-01-08',
    status: '活跃'
  }
])

// 对话框
const showSettingsDialog = ref(false)

// 设置表单
const settingsForm = reactive({
  refreshInterval: 0,
  defaultTimeRange: 'month',
  visibleModules: ['sales', 'inventory', 'customer', 'product', 'profit'],
  defaultGranularity: 'day'
})

// 图表引用
const salesChartRef = ref(null)
const channelChartRef = ref(null)
const regionChartRef = ref(null)
const categoryChartRef = ref(null)
const customerValueChartRef = ref(null)
const inventoryTurnoverChartRef = ref(null)
const profitChartRef = ref(null)

let salesChart = null
let channelChart = null
let regionChart = null
let categoryChart = null
let customerValueChart = null
let inventoryTurnoverChart = null
let profitChart = null

// 初始化图表
const initCharts = () => {
  // 销售趋势图
  if (salesChartRef.value) {
    salesChart = echarts.init(salesChartRef.value)
    const option = {
      tooltip: { trigger: 'axis' },
      legend: { data: ['销售额', '利润'] },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: '销售额',
          type: 'line',
          data: [1200, 1320, 1010, 1340, 900, 2300, 2100, 1820, 1910, 2340, 2900, 3300],
          smooth: true,
          itemStyle: { color: '#409eff' }
        },
        {
          name: '利润',
          type: 'line',
          data: [220, 282, 191, 234, 290, 330, 310, 320, 329, 390, 580, 660],
          smooth: true,
          itemStyle: { color: '#67c23a' }
        }
      ]
    }
    salesChart.setOption(option)
  }

  // 渠道占比图
  if (channelChartRef.value) {
    channelChart = echarts.init(channelChartRef.value)
    const option = {
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'left' },
      series: [
        {
          name: '销售渠道',
          type: 'pie',
          radius: '50%',
          data: [
            { value: 1048, name: '线上商城' },
            { value: 735, name: '线下门店' },
            { value: 580, name: '分销渠道' },
            { value: 484, name: '企业直销' }
          ]
        }
      ]
    }
    channelChart.setOption(option)
  }

  // 区域分布图
  if (regionChartRef.value) {
    regionChart = echarts.init(regionChartRef.value)
    const option = {
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: ['华北', '华东', '华南', '华中', '西南', '西北', '东北']
      },
      yAxis: { type: 'value' },
      series: [
        {
          data: [1200, 2000, 1500, 800, 700, 500, 600],
          type: 'bar',
          itemStyle: { color: '#409eff' }
        }
      ]
    }
    regionChart.setOption(option)
  }

  // 产品类别图
  if (categoryChartRef.value) {
    categoryChart = echarts.init(categoryChartRef.value)
    const option = {
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      legend: { data: ['本月', '上月'] },
      xAxis: {
        type: 'category',
        data: ['手机', '电脑', '配件', '家电', '其他']
      },
      yAxis: { type: 'value' },
      series: [
        {
          name: '本月',
          type: 'bar',
          data: [1200, 900, 800, 600, 400],
          itemStyle: { color: '#409eff' }
        },
        {
          name: '上月',
          type: 'bar',
          data: [1050, 850, 720, 580, 380],
          itemStyle: { color: '#67c23a' }
        }
      ]
    }
    categoryChart.setOption(option)
  }

  // 客户价值图
  if (customerValueChartRef.value) {
    customerValueChart = echarts.init(customerValueChartRef.value)
    const option = {
      tooltip: { trigger: 'item' },
      series: [
        {
          name: '客户价值',
          type: 'pie',
          radius: ['40%', '70%'],
          data: [
            { value: 335, name: '高价值' },
            { value: 310, name: '中价值' },
            { value: 234, name: '低价值' }
          ]
        }
      ]
    }
    customerValueChart.setOption(option)
  }

  // 库存周转图
  if (inventoryTurnoverChartRef.value) {
    inventoryTurnoverChart = echarts.init(inventoryTurnoverChartRef.value)
    const option = {
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: ['Q1', 'Q2', 'Q3', 'Q4']
      },
      yAxis: { type: 'value', name: '次' },
      series: [
        {
          data: [4.2, 4.5, 4.8, 5.2],
          type: 'line',
          smooth: true,
          itemStyle: { color: '#e6a23c' }
        }
      ]
    }
    inventoryTurnoverChart.setOption(option)
  }

  // 利润率图
  if (profitChartRef.value) {
    profitChart = echarts.init(profitChartRef.value)
    const option = {
      tooltip: { trigger: 'axis' },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: { type: 'value', name: '%' },
      series: [
        {
          data: [35.2, 36.8, 38.5, 37.2, 39.1, 38.5],
          type: 'line',
          smooth: true,
          areaStyle: { color: 'rgba(103, 194, 58, 0.2)' },
          itemStyle: { color: '#67c23a' }
        }
      ]
    }
    profitChart.setOption(option)
  }
}

// 窗口大小改变时重绘图表
const handleResize = () => {
  salesChart?.resize()
  channelChart?.resize()
  regionChart?.resize()
  categoryChart?.resize()
  customerValueChart?.resize()
  inventoryTurnoverChart?.resize()
  profitChart?.resize()
}

// 方法
const getRankType = (rank) => {
  const types = { 1: 'danger', 2: 'warning', 3: 'success' }
  return types[rank] || ''
}

const getCustomerStatusType = (status) => {
  const types = {
    '活跃': 'success',
    '休眠': 'warning',
    '流失': 'danger'
  }
  return types[status] || 'info'
}

const handleSearch = () => {
  console.log('查询', filterForm)
  ElMessage.success('数据查询成功')
}

const handleRefresh = () => {
  ElMessage.success('数据刷新成功')
}

const refreshTable = () => {
  ElMessage.success('表格数据刷新成功')
}

const saveSettings = () => {
  console.log('保存设置', settingsForm)
  ElMessage.success('设置保存成功')
  showSettingsDialog.value = false
}

onMounted(() => {
  setTimeout(() => {
    initCharts()
  }, 100)
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  salesChart?.dispose()
  channelChart?.dispose()
  regionChart?.dispose()
  categoryChart?.dispose()
  customerValueChart?.dispose()
  inventoryTurnoverChart?.dispose()
  profitChart?.dispose()
  window.removeEventListener('resize', handleResize)
})
</script>

<style scoped lang="scss">
.bi-dashboard-page {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  h2 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }
}

.filter-card {
  margin-bottom: 20px;
}

.kpi-row {
  margin-bottom: 20px;
}

.kpi-card {
  display: flex;
  align-items: center;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s;

  &:hover {
    transform: translateY(-4px);
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  }

  .kpi-icon {
    width: 70px;
    height: 70px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20px;
    color: white;
  }

  .kpi-content {
    flex: 1;

    .kpi-label {
      font-size: 14px;
      color: #909399;
      margin-bottom: 8px;
    }

    .kpi-value {
      font-size: 32px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 8px;
    }

    .kpi-footer {
      display: flex;
      align-items: center;
      gap: 8px;

      .kpi-compare {
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 14px;
        font-weight: 500;
      }

      .kpi-desc {
        font-size: 12px;
        color: #909399;
      }
    }
  }

  &.positive .kpi-compare {
    color: #67c23a;
  }

  &.negative .kpi-compare {
    color: #f56c6c;
  }
}

.chart-card {
  margin-bottom: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .title {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .chart-container {
    height: 350px;
  }
}

.table-card {
  :deep(.el-card__body) {
    padding-top: 0;
  }
}
</style>

